将 JSON feed 与 Backbone JS 集成

发布于 2024-11-01 00:42:10 字数 7285 浏览 1 评论 0原文

我目前正在开发一个项目,在该项目中,我在输入框中键入关键字,当我单击“发送”时,它会使用类似 (localhost/json-status.php?query=input text) 并以 json 格式返回“query=”后面的内容。现在我已经用 jQuery 完成了这个任务,并且我正在尝试在主干 js 中再次完成这个任务。

$("#updateStatus").click(function(){

   var query = $("#statusBar").val();

   var url = "json-status.php" + "?query=" + query;

   $.getJSON(url,function(json){
            $.each(json.posts,function(i,post){
         $("#content").append(
            '<div>'+
               '<p>'+post.status+'</p>'+
            '</div>'
         );
      });
   });
});

我已经将我在 jQuery 中所做的大部分内容移植到了主干 js 上,但到目前为止并没有按预期工作,请让我知道我的方法是否正确以及如何解决我的问题。

主干代码:

(function ($) {
   Status = Backbone.Model.extend({
      status: null
   });

   StatusList = Backbone.Collection.extend({
      initialize: function (models, options) {
         this.bind("add", options.view.addStatusList);
      }
   });

   AppView = Backbone.View.extend({
      el: $("body"),
      initialize: function () {
         this.status = new StatusList( null, { view: this });
      },
      events: {
         "click #updateStatus":   "getStatus",
      },
      getStatus: function () {
         var url = "json-status.php" + "?query=" + $("#statusBar").val();
         var statusModel;

         $.getJSON(url,function(json){
            $.each(json.posts,function(i,post){
               statusModel = new Status({ status: post.status });
               this.status.add( statusModel );
            });
         });
      },
      addStatusList: function (model) {
         $("#status").prepend("<div>" + model.get('status') + "</div>");
      }
   });

   var appview = new AppView;
})(jQuery);

以 json 格式返回的 PHP 服务器代码(这很好用):

<?php
    $getQuery = $HTTP_GET_VARS["query"];

    $json='
    {"posts":[
        {
            "status": "' . $getQuery . '"
        }
    ]}
    ';
    echo $json;
?>

如果您想复制/粘贴我到目前为止所拥有的内容,那就是:

<!DOCTYPE html>
<html>
<head>
    <title>JSON Test</title>
</head>
<body>

    <input value="What's on your mind?" id="statusBar" /><button id="updateStatus">Update Status</button>

    <div id="content">

    </div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>

    <script type="text/javascript">
        $("#statusBar").click(function() {
            $(this).val("");
        });

        (function ($) {
            Status = Backbone.Model.extend({
                status: null
            });

            StatusList = Backbone.Collection.extend({
                initialize: function (models, options) {
                    this.bind("add", options.view.addStatusList);
                }
            });

            AppView = Backbone.View.extend({
                el: $("body"),
                initialize: function () {
                    this.status = new StatusList( null, { view: this });
                },
                events: {
                    "click #updateStatus":  "getStatus",
                },
                getStatus: function () {
                    var url = "json-status.php" + "?query=" + $("#statusBar").val();
                    var statusModel;

                    $.getJSON(url,function(json){
                        $.each(json.posts,function(i,post){
                            statusModel = new Status({ status: post.status });
                            this.status.add( statusModel );
                        });
                    });
                },
                addStatusList: function (model) {
                    $("#status").prepend("<div>" + model.get('status') + "</div>");
                }
            });

            var appview = new AppView;
        })(jQuery);
    </script>

</body>
</html>

谢谢您的时间。


朱利安的密码。

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

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(this.status.value);
    },
    render: function () {
        var statusEl = $("#status");
        this.status.each( function(model) {
            statusEl.prepend("<div>" + model.get('status') + "</div>");
        });
    }
});

var appview = new AppView;

完整 HTML(第 2 部分):

<!DOCTYPE html>
    <html>
    <head>
        <title>JSON Test</title>
    </head>
    <body>

        <input value="What's on your mind?" id="statusBar" />
        <button id="updateStatus">Update Status</button>

        <div id="status">

        </div>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
        <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
        <script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>

        <script type="text/javascript">
            $("#statusBar").click(function() {
                $(this).val("");
            });

            Status = Backbone.Model.extend();

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

            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(this.status.value);
                },
                render: function () {
                    var statusEl = $("#status");
                    this.status.each( function(model) {
                        statusEl.prepend("<div>" + model.get('status') + "</div>");
                    });
                }
            });

            var appview = new AppView;

        </script>

    </body>
    </html>

PHP 与最初记录的 PHP 仍然相同。

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=input text) and it returns whatever is after "query=" in json format. Now I've accomplished this with jQuery and I'm trying to do this again in backbone js.

$("#updateStatus").click(function(){

   var query = $("#statusBar").val();

   var url = "json-status.php" + "?query=" + query;

   $.getJSON(url,function(json){
            $.each(json.posts,function(i,post){
         $("#content").append(
            '<div>'+
               '<p>'+post.status+'</p>'+
            '</div>'
         );
      });
   });
});

I've pretty much ported over what I did in jQuery over to backbone js and it's not working out as expected so far, please let me know if my approach is correct and how I can solve my problem.

backbone code:

(function ($) {
   Status = Backbone.Model.extend({
      status: null
   });

   StatusList = Backbone.Collection.extend({
      initialize: function (models, options) {
         this.bind("add", options.view.addStatusList);
      }
   });

   AppView = Backbone.View.extend({
      el: $("body"),
      initialize: function () {
         this.status = new StatusList( null, { view: this });
      },
      events: {
         "click #updateStatus":   "getStatus",
      },
      getStatus: function () {
         var url = "json-status.php" + "?query=" + $("#statusBar").val();
         var statusModel;

         $.getJSON(url,function(json){
            $.each(json.posts,function(i,post){
               statusModel = new Status({ status: post.status });
               this.status.add( statusModel );
            });
         });
      },
      addStatusList: function (model) {
         $("#status").prepend("<div>" + model.get('status') + "</div>");
      }
   });

   var appview = new AppView;
})(jQuery);

PHP server code which returns in json format (this works fine):

<?php
    $getQuery = $HTTP_GET_VARS["query"];

    $json='
    {"posts":[
        {
            "status": "' . $getQuery . '"
        }
    ]}
    ';
    echo $json;
?>

And if you wish to copy/paste what I have so far it's:

<!DOCTYPE html>
<html>
<head>
    <title>JSON Test</title>
</head>
<body>

    <input value="What's on your mind?" id="statusBar" /><button id="updateStatus">Update Status</button>

    <div id="content">

    </div>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>

    <script type="text/javascript">
        $("#statusBar").click(function() {
            $(this).val("");
        });

        (function ($) {
            Status = Backbone.Model.extend({
                status: null
            });

            StatusList = Backbone.Collection.extend({
                initialize: function (models, options) {
                    this.bind("add", options.view.addStatusList);
                }
            });

            AppView = Backbone.View.extend({
                el: $("body"),
                initialize: function () {
                    this.status = new StatusList( null, { view: this });
                },
                events: {
                    "click #updateStatus":  "getStatus",
                },
                getStatus: function () {
                    var url = "json-status.php" + "?query=" + $("#statusBar").val();
                    var statusModel;

                    $.getJSON(url,function(json){
                        $.each(json.posts,function(i,post){
                            statusModel = new Status({ status: post.status });
                            this.status.add( statusModel );
                        });
                    });
                },
                addStatusList: function (model) {
                    $("#status").prepend("<div>" + model.get('status') + "</div>");
                }
            });

            var appview = new AppView;
        })(jQuery);
    </script>

</body>
</html>

Thank you for your time.


Julien's code.

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

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(this.status.value);
    },
    render: function () {
        var statusEl = $("#status");
        this.status.each( function(model) {
            statusEl.prepend("<div>" + model.get('status') + "</div>");
        });
    }
});

var appview = new AppView;

Full HTML (part 2):

<!DOCTYPE html>
    <html>
    <head>
        <title>JSON Test</title>
    </head>
    <body>

        <input value="What's on your mind?" id="statusBar" />
        <button id="updateStatus">Update Status</button>

        <div id="status">

        </div>

        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
        <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
        <script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>

        <script type="text/javascript">
            $("#statusBar").click(function() {
                $(this).val("");
            });

            Status = Backbone.Model.extend();

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

            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(this.status.value);
                },
                render: function () {
                    var statusEl = $("#status");
                    this.status.each( function(model) {
                        statusEl.prepend("<div>" + model.get('status') + "</div>");
                    });
                }
            });

            var appview = new AppView;

        </script>

    </body>
    </html>

And the PHP is still the same from the one originally documented.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乱世争霸 2024-11-08 00:42:10

至于您的一般设计,您应该使用 Backbone.ModelCollection 来获取您的状态:

Status = Backbone.Model.extend();

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

您的视图应该监听 StatusList 而不是创建绑定的 StatusList视图:

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>");
    }
  }
});

这里有几件事:

  • 模型上的属性是通过 set/get 定义的,而不是像状态那样由 js 属性定义。
  • 尝试将视图了解模型的内容分离,但模型不了解视图

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
季末如歌 2024-11-08 00:42:10

供参考
(来自文档)

我们借此机会澄清了 0.5.0 版本的一些命名。控制器现在是路由器,并且刷新现已重置

因此,如果您使用的是最新版本,请不要忘记将这一行中的刷新更改为重置

this.status.bind("refresh", this.render);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文