Integrating JSON feed with Backbone JS

前端 未结 2 1468
长情又很酷
长情又很酷 2021-02-04 20:36

I\'m currently working on a project where I type a keyword inside an input box and when I click send it hits a PHP server with a link like (localhost/json-status.php?query=

2条回答
  •  情歌与酒
    2021-02-04 20:56

    As for your general design, you should use a Backbone.Model and Collection to fetch your statuses:

    Status = Backbone.Model.extend();
    
    StatusList = Backbone.Collection.extend({
      model: Status,
      value: null
      url: function(){ return "json-status.php" + "?query=" + this.value;
    });
    

    Your view should be listening to the StatusList and not the StatusList creating a binding to the view:

    AppView = Backbone.View.extend({
      el: $("body"),
      initialize: function () {
        _.bindAll(this, "render");// to solve the this issue
        this.status = new StatusList( null, { view: this });
        this.status.bind("refresh", this.render);
      },
      events: {
        "click #updateStatus":  "getStatus",
      },
      getStatus: function () {
        this.status.value =  $("#statusBar").val();
        this.status.fetch()
      },
      render: function () {
        var statusEl = $("#status")
        this.status.each( function(model){
          statusEl.prepend("
    " + model.get('status') + "
    "); } } });

    There is a couple of things here:

    • an attribute on the model is defined by set/get not by a js attributes like you did with status
    • try to decouple stuff views know about models but models do not know about views

提交回复
热议问题