mheavers
mheavers

Reputation: 30158

backbone - losing scope of objects and functions in ajax calls

I'm new to backbone and I'm trying to understand how to maintain scope in my views. In javascript I typically set up an object as a sort of class, and use self = this to maintain scope of the overall class. I'm trying to do the same thing in backbone. I have this sort of set up:

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

So you can see on the last line I'm trying to maintain reference to my tweets array so I can push each tweet to it, but it cannot find the array tweets. How do I keep this scope?

Upvotes: 0

Views: 397

Answers (3)

mheavers
mheavers

Reputation: 30158

I figured this out - with jquery ajax you can use context: this as an object parameter, so then inside you can still refer to this.tweets

Upvotes: 1

wachme
wachme

Reputation: 2337

app.TwitterView is a type (class), which you can create instance of. So you have to refer to the current instance (this), not class name:

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;

Upvotes: 0

benhowdle89
benhowdle89

Reputation: 37464

Can also use .bind() to keep scope:

  $.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)

No need for var self = this; then...

Upvotes: 0

Related Questions