How do I fetch a single model in Backbone?

前端 未结 7 1112
误落风尘
误落风尘 2020-11-30 18:36

I have a Clock model in Backbone:

var Clock = Backbone.Model.extend({});

I\'m trying to get an instance of that that has the l

7条回答
  •  情话喂你
    2020-11-30 19:11

    I personally recommend, following the Model#url method documentation

    model = new Model(id: 1)
    view = new View(model: model) 
    collection = new Collection([model])
    model.fetch()
    

    in your collection remember to add the collection url:

    url: "/models"
    

    and in your View's initialize function do:

    this.model.bind("change", this.render)
    

    this way backbone will do an ajax request using this url:

    "/models/1"
    

    your model will be updated and the view rendered, without modifying Collection#url or Model#urlRoot

    note: sorry this example came out in coffee script, but you can easily translate it to js adding var statements

提交回复
热议问题