Javascript 主干-在ajax调用中丢失对象和函数的范围
我是主干网的新手,我正在努力理解如何在我的视图中维护范围。在javascript中,我通常将对象设置为类,并使用self=this来维护整个类的范围。我正试着在脊梁骨上做同样的事情。我有这样的设置:Javascript 主干-在ajax调用中丢失对象和函数的范围,javascript,ajax,backbone.js,scope,backbone-views,Javascript,Ajax,Backbone.js,Scope,Backbone Views,我是主干网的新手,我正在努力理解如何在我的视图中维护范围。在javascript中,我通常将对象设置为类,并使用self=this来维护整个类的范围。我正试着在脊梁骨上做同样的事情。我有这样的设置: var app = app || {}; app.TwitterView = Backbone.View.extend({ el: '#twitter-container', tweets: [], initialize: function( templateContent ) {
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);
var-app=app | |{};
app.TwitterView=Backbone.View.extend({
el:“#推特容器”,
tweets:[],
初始化:函数(templateContent){
这个.render(模板内容);
},
呈现:函数(templateContent){
this.$el.html(this.template(templateContent));
this.loadTweets();
归还这个;
},
loadTweets:function(){
log(“加载tweets”);
this.tweets=[];
clearInterval(this.tweetCheckInterval,this.tweetCycleInterval);
$.ajax({
url:“scripts/php/mixitup.php”,
键入:“获取”,
数据类型:“json”,
cache:false,
成功:功能(数据){
控制台日志(数据);
for(var i=0;iapp.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;
也可以使用.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)
$.ajax({
url:“scripts/php/mixitup.php”,
键入:“获取”,
数据类型:“json”,
cache:false,
成功:功能(数据){
控制台日志(数据);
对于(var i=0;i我发现了这一点-通过jquery ajax,您可以使用上下文:这是一个对象参数,所以在内部您仍然可以引用它。tweets如何调用loadTweets
?啊,对不起-请看更新的问题。我已经尝试过了-如果我使用self,那么当我尝试从ajax成功调用中记录它时,我会得到DOM的一个范围此视图应用到的元素。不是此对象中包含的所有函数,例如tweets(我需要)@mheavers-oops,可以吗?