普通网友 2017-02-01 05:29
浏览 18

骨干事件行为

I'm just getting started with backbone, and I have run into a very confusing wall.

What I am doing:

  1. Create a model instance of type A that calls fetch during initialization.
  2. Create a model instance of type B that calls fetch during initialization.
  3. Create a view that uses data from both.
  4. Bind the sync event from both of the models to view.render(), and create a table once both AJAX calls have returned (render will be called twice, I know - not a big deal).

What I am expecting is that when the second sync event hits, the table is rendered using data from both.

What is actually happening is that the sync event is firing, but the model data is completely empty when the view tries to use it (I can check the model.cid and see that it is the same model that I created initially, it just contains absolutely nothing). I have logging so that I can tell which event is firing from which model, and I can see render being called twice as expected.

I can add a debug button to my page that calls the same render manually (once both AJAX calls have completed), and everything renders just fine, so I know both my AJAX calls were ultimately successful and did eventually result in a fully populated model.

What am I doing wrong? Am I fundamentally misunderstanding what an event is supposed to do here? Why would my model be completely empty after a sync event?

Dave

  • 写回答

1条回答 默认 最新

  • weixin_33671935 2017-02-02 03:59
    关注

    Apologies for the rather poor question, replete with its lack of actual code. I went through and re-wrote everything from scratch, made it work, then went back through my original code line by line to figure out why it didn't work.

    Let's just say that there is a big difference between this:

    this.listenTo(user, 'sync', this.render("userchange"));
    

    and this:

    this.listenTo(user, 'sync', this.render);
    

    I need to read up on on "passing a function" vs "running a function".

    Dave

    评论

报告相同问题?