-1

I want to change a background image of a div by css using the json data returned using Emberjs. However the background image doesn't change in the following code.

However when I remove the return and put the after model code within the model it changes the background image, what is the problem in the code and how can I fix it? Thanks

App.ERoute = Ember.Route.extend({
    model: function()
    {
        var json = $.getJSON('url').done(function(result){
            return result;   
        });
    return json;
    },
    afterModel : function(model)
    {

        $('#eventheader::shadow #headerBg').css('background-image' , 'url(' + model.image + ')';
    }
});
rksh
  • 3,920
  • 10
  • 49
  • 68
  • what does the `::` do in your selector? have you tried just running the selector in the javascript console to ensure you're getting the elements you're interested in? – DLeh Nov 24 '14 at 18:35
  • well :: because I'm using the Polymer material design framework, it's the way they've named it – rksh Nov 24 '14 at 18:36
  • `:` also has it's own meaning in jquery selectors, and might be throwing it off. Run `$('#eventheader::shadow #headerBg')` in your browser's console to see if it returns the elements you're expecting – DLeh Nov 24 '14 at 18:37
  • 2
    Two words: [asynchronous execution](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). – hon2a Nov 24 '14 at 18:41
  • @hon2a But I'm using a callback isn't it? – rksh Nov 24 '14 at 19:00
  • 2
    Agree with @hon2a, you return json BEFORE the .done is completed – Max Nov 24 '14 at 19:17
  • Ok i changed the code to this but no effect model: function() { return Em.RSVP.hash({ event : Ember.$.getJSON('url') }); }, afterModel : function(model) { $('#eventheader::shadow #headerBg').css('background-image' , 'url(' + model.event.image + ')'); } – rksh Nov 24 '14 at 19:33

1 Answers1

0

Doing the background change in the model hook of the route is not the-ember-way. Do that in your view, that is where you should perform presentation/view logic.

For your code to work, you need to use promises, something like:

model: function() {
  return Ember.$.getJSON('url').then(function() {
    // perform some logic
  });
},

afterModel : function(model) {
  // this hook executes once the promise returned by model resolves
  $('#eventheader::shadow #headerBg').css...
}

Ember transitions are blocked until beforeModel, model and afterModel are resolved. Your transition won't complete (the view won't be rendered) until all of those hooks return a resolved promise or something that is not a promise.

read:

http://emberjs.com/api/classes/Ember.Route.html#method_model

http://emberjs.com/guides/understanding-ember/managing-asynchrony/

givanse
  • 14,503
  • 8
  • 51
  • 75
  • can you give me the answer with ember view then, this code is similar to what I have posted in the question and won't work – rksh Nov 24 '14 at 21:01