lundi 29 février 2016

Data binding broken after putting raw ajax json in models

First I had this code in routes/index.js:

        hotspots:ajax( {
          url: 'url-to-external-api',
          type: 'get'
        } ).then( function( data ) {
          console.log( 'hotspots: ', data );
          return data;
        } )

I changed this to:

hotspots: this.store.findAll( 'hotspot' )

And in models/hotspot.js:

import DS from "ember-data";

export default DS.Model.extend( {
  about: DS.attr( ),
  category: DS.attr( ),
  hide_directions: DS.attr( ),
  image_highres: DS.attr( ),
  image_lowres: DS.attr( ),
  images: DS.attr( ),
  lat: DS.attr( ),
  lng: DS.attr( ),
  name: DS.attr( ),
  order: DS.attr( ),
  timestamp: DS.attr( ),
  x_axis: DS.attr( ),
  y_axis: DS.attr( )
} );

In adapters/hotspot.js:

import DS from 'ember-data';

export default DS.Adapter.extend( {
  findAll: function( store, type, sinceToken ) {
    var url = type;
    var query = {
      since: sinceToken
    };
    return new Ember.RSVP.Promise( function( resolve, reject ) {
      Ember.$.getJSON( "url-to-external-api" ).then( function( data ) {
        console.log( data );
        Ember.run( null, resolve, data );
      }, function( jqXHR ) {
        jqXHR.then = null; // tame jQuery's ill mannered promises
        Ember.run( null, reject, jqXHR );
      } );
    } );
  }
} );

When I used the ajax call in routes/index.js, I edited some of the properties of some hotspots in the array. And it would directly be updated in my app through 2-way data-binding. Now that I'm using models, I don't have this data-binding anymore.

At first I used this code in an action to change some of the properties of the hotspots:

  for ( let value of this.currentModel.hotspots ) {
    if ( value.id === hotspotId ) {
      console.log( value );
      Ember.set( value, "x_axis", event.offsetX );
      Ember.set( value, "y_axis", event.offsetY );
    }
  }

Now I'm using this:

  for ( let value of this.currentModel.hotspots.content ) {
    if ( value.id === hotspotId ) {
      console.log( value );
      Ember.set( value._data, "x_axis", event.offsetX );
      Ember.set( value._data, "y_axis", event.offsetY );
    }
  }

Which isn't working anymore.

How can I resolve this? Models are best practice, but for what? They are just a pain and working with raw ajax calls is way more easy and straight-forward...




Aucun commentaire:

Enregistrer un commentaire