Integrating JSON feed with Backbone JS

前端 未结 2 1463
长情又很酷
长情又很酷 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("<div>" + model.get('status') + "</div>");
        }
      }
    });
    

    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
    0 讨论(0)
  • 2021-02-04 21:07

    FYI (from the documentation)

    We've taken the opportunity to clarify some naming with the 0.5.0 release. Controller is now Router, and refresh is now reset.

    So if you are using the latest version dont forget to change refresh to reset in this line:

    this.status.bind("refresh", this.render);
    
    0 讨论(0)
提交回复
热议问题