简体   繁体   中英

How to pass back model attribute from a view Backbone

I have a controller:

            var layout = new LayoutView();
            App.holder1.show(layout);
            var my_view = new myView({id: options})
            layout.holder1.show();

            console.log(my_view.model.get('name')) <---- I want this

I want to get my_view.model.get('name') however, the issue is I get undefined . I have console.log the model and it is populated ok, however I think it's because it's not fully loaded yet when I try the get.

This is my current thisView:

  var thisView = Backbone.Marionette.ItemView.extend({
            initialize: function (options) {
                this.model.fetch();
            },
            model: new myModel(),
            template: testExampleTemplate,
        });
        return thisView;

You'll have the object populated only after the success callback function:

initialize: function (options) {
  this.model.fetch({
    success: function(model){
      console.log(model.get('name'));
    };
  });
}

Listen for an event. "change" or "reset" will work.

viewInstance.model.on("change", function(){
    viewInstance.model.get("nameOfAttribute");
    // do something
});

http://backbonejs.org/#Events-catalog

There's a few ways to approach this. First, you could listen for a change event from the model in the view, and do whatever it is you need when the change event fires. If you need to do something no matter what, you have a couple of options: you could write an implementation for you model's parse method that fires an event your view listens for and does something in response, or you can do something in the success callback for the fetch method itself (passed as an option to fetch). I can provide an example if I understand better which approach makes sense for your situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM