2014년 12월 8일 월요일

[backbonejs] backbone weird behavior...change

As I updated backbone to the newest version, I made some changes to the code-I changed this:

this.collection.bind('reset', this.addAll);
            this.collection.bind('add', this.addOne);
            this.collection.bind('change', this.change);
            this.collection.bind('destroy', this.destroy);
with this:
    this.listenTo(this.collection,'add', this.addOne);
            this.listenTo(this.collection,'change', this.change);
            this.listenTo(this.collection,'destroy', this.destroy);
            this.listenTo(this.collection,'reset', this.addAll);


A jsbin demo is here...
And now the weird staff...
When you go to add an event in jsbin...two functions are called,save and addOne(you can see that through the console.)
In my local environment though the change function is also called which is normally called only when you go to change the details on event...strange.

After a little search I made the cause is located in this line:
 this.model.set({'title': this.$('#name').val(),'origin':this.$('#origin').val(),'staff':this.$("#staff").val(),'services':14});

And more the specifically the server response the line causes...the above line sends some data to the server....if the server responds successfully it sends this JSON back(example):

{"id":70,"service":14,"staff_ID":["14"]}

This flow above as I describe it will fire the change function.
But if in the model.set line above change one of the names of the keys(from services to serv for example) the server will send an error back(missing index),something to be expected as the server script accepts "services" and not 'serv',but on the other hand change will not fire.

I cannot understand why this happens...furthermore it is impossible to demonstrate this with jsbin as it is implies server response/activity.
And I am not sure at all that the change function is called due to server response...probably not.


The question boils down to this....why the "change" event is fired,since no model attributes are changed....
Of course the "add" event is fired too but this is welcomed.



change event can be fired from set method, and set method is called when new instance of model is created



Was that always this case....I mean with older backbone version too?
That the change event was fired with set.



I can't truly remember. It was several years ago.



Yes "change" was fires also in older backbone vesions...there is a difference though.
In the jsbin demo I gave in the older version, the change function was not fired....now it is fired.



Take a look this jsbin here.It uses the latest backbone version...the change function is not fired though.
The change event is fired probably yes...but the change function you see in the code is not. 


댓글 없음:

댓글 쓰기