简体   繁体   中英

Backbone refresh collection with event handler

I'm using backbone and I'm very new at it, I have a list of products sizes and a list of quantities / prices. When someone selects a different product size, I use backbone to do an ajax call to the server to get me an updated price list.

I'm struggling to get the save function to work so that I can return the updated collection. I will have to pass back a couple params, but for the time being, I'm just trying to get it to save to the backend. I've read save can be used to automatically setup the ajax request.

I'd also only like this to load the template when the li element is clicked, not on page load.

My code

var models = {};

models.PriceModel = Backbone.Model.extend({   

})

models.PriceList = Backbone.Collection.extend({

    initialize: function(options) {     
        this.productId = options.productId;
    },

    model: models.PriceModel,

    url: function() {
           return '../product/pricing/' + this.productId + '.json'
        }  

});

View

var PriceView = Backbone.View.extend({
    el: '#product-module',

    template: Handlebars.compile($("#priceTemplate").html()),

    events: {
        "click #product-dimensions li": "dimensionClicked",
    },

    initialize: function(){
        this.listenTo(this.collection, 'add', this.render);
        this.listenTo(this.collection, 'reset', this.render);
    },

    render: function() {
        this.$el.find('#product-quantities').html( this.template(this.collection.toJSON()));
    },

    dimensionClicked: function(event, callback){        
        this.collection.save({},{
              success: function(model, data){
                  console.log('success')
                  this.collection.fetch();
              },
              error: function(model, response) {
                  console.log('error! ' + response);
              }
          });
    },

});

Page

<script>   
    var prices = new models.PriceList({productId:${productInstance.id}});
    var priceView = new PriceView({collection: prices});
<%--        prices.fetch({reset: true});--%>
</script>

The error I'm getting.

TypeError: this.collection.save is not a function

this.collection.save({},{

How do I pass back a couple of params and then refresh the template?

解决方案是使用

this.collection.fetch({data: {customParm : searchData}, reset: true});

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