主干-ajax调用中对象和函数的作用域丢失

backbone - losing scope of objects and functions in ajax calls

本文关键字:作用域 函数 -ajax 调用 对象 主干      更新时间:2023-09-26

我是主干网的新手,我正在努力了解如何在视图中维护范围。在javascript中,我通常将对象设置为一类,并使用self-this来维护整个类的范围。我正努力在骨气上做同样的事情。我有这样的设置:

var app = app || {};
app.TwitterView = Backbone.View.extend({
  el: '#twitter-container',
  tweets: [],
  initialize: function( templateContent ) {
    this.render(templateContent);
  },
  render: function(templateContent) {
    this.$el.html(this.template(templateContent));
    this.loadTweets();
    return this;
  },
  loadTweets: function(){
      console.log('load tweets');
      this.tweets = [];
      clearInterval(this.tweetCheckInterval,this.tweetCycleInterval);
      $.ajax({
        url: "scripts/php/mixitup.php",
        type: "GET",
        dataType: 'json',
        cache: false,
        success: function (data) {
          console.log(data);
          for (var i=0; i<data.statuses.length;i++){
            var tweet = {};
            tweet.status = data.statuses[i].text;
            tweet.user = data.statuses[i].user.screen_name;
            app.TwitterView.tweets.push(tweet);

所以你可以在最后一行看到,我试图保持对tweets数组的引用,这样我就可以将每条tweet推送到它,但它找不到数组tweets。如何保留此范围?

我发现了这一点-使用jquery ajax,您可以使用context:this作为对象参数,因此在内部您仍然可以引用this.tweets

还可以使用.bind()来保持作用域:

  $.ajax({
    url: "scripts/php/mixitup.php",
    type: "GET",
    dataType: 'json',
    cache: false,
    success: function (data) {
      console.log(data);
      for (var i=0; i<data.statuses.length;i++){
        var tweet = {};
        tweet.status = data.statuses[i].text;
        tweet.user = data.statuses[i].user.screen_name;
        this.tweets.push(tweet);
      }
    }.bind(this)

那么就不需要var self = this;了。。。

app.TwitterView是一个类型(类(,您可以创建它的实例。因此,您必须引用当前实例(this(,而不是类名:

var app = app || {};
app.TwitterView = Backbone.View.extend({
  el: '#twitter-container',
  tweets: [],
  loadTweets: function(){
      var self = this;
      $.ajax({
        url: "scripts/php/mixitup.php",
        type: "GET",
        dataType: 'json',
        cache: false,
        success: function (data) {
          console.log(self.tweets) //need to be able to access that tweets array here.
          debugger;