2012-11-02 25 views
0

我已經採用了一個項目,它定義了幾個對象文字 - 主要是爲了構造代碼。順便說一句,不是一個全職的前端開發人員。問題是它們中的一些是使用jQuery onready事件定義的,有些則在外面。至少可以說這似乎是很有問題的。這會被認爲是不好的設計?我假設如此。我已經包含的代碼片段顯示了一些問題,特別是OBJ2內的from_inside功能:訪問使用jQuery onready定義的對象字面值from

<script> 
$(document).ready(function(){ 
    alert('here i am' + obj2.handlers2.background2); // can access the obj2 value as expected 
    alert('make this up: ' + obj2.handlers2.tell_me2()); 
    var obj={}; 
    obj.handlers={ 
    background: 'blue', 
    foreground: 'green' 
    } 
}); 

var obj2={}; 
obj2.handlers2={ 
    background2: 'here i am jt', 
    foreground2: 'there you are', 
    tell_me2: function(){ 
    return "these are things"; 
    } 
    , 
    from_inside: function(){ 
    alert('color from inside jQuery: ' + obj.handlers.background); // problem here! could I get a reference to obj here? 
    } 
}; 

obj2.handlers2.from_inside(); 

</script> 

鑑於我們當前如何擁有它,這將是一個最好的解決方法?看起來好像我可以在上面將jQuery對象的引用傳遞給obj2,但也許可能只是簡單地將jQuery之外的所有對象都準備好,即使可能的話也是如此。

事先THX的任何建議

編輯#1

$(document).ready(function(){ 
    $(document).on('click','#pairing-comment-submit', function(){ 
    arc.event_handler.submit_pairing_comment.call(this); 
    }); 
    ... about 50 more of these 
}); 

arc={}; 
arc.event_handler={ 
    submit_pairing_comment: function(){ 
    var id=$(this).data('the-id'); 
    .... 
    }, 
    .... 
} 
+0

剛剛做了一個快速重構。讓我知道這是否有幫助。 –

回答

2

您可以移動就緒功能以外的變量賦值。這裏有一個快速重構:

var obj={}; 
obj.handlers={ 
    background: 'blue', 
    foreground: 'green' 
}; 

var obj2={}; 
obj2.handlers2={ 
    background2: 'here i am jt', 
    foreground2: 'there you are', 
    tell_me2: function(){ 
    return "these are things"; 
    }, 
    from_inside: function(){ 
    alert('color from inside jQuery: ' + obj.handlers.background); // problem here! could I get a reference to obj here? 
    } 
}; 

$(document).ready(function(){ 
    alert('here i am' + obj2.handlers2.background2); // can access the obj2 value as expected 
    alert('make this up: ' + obj2.handlers2.tell_me2()); 
    obj2.handlers2.from_inside(); 
}); 

工作例如:http://jsfiddle.net/JxS7v/

你所面臨的問題是由於變量的作用域。一般來說,變量的範圍是它們所在的功能。看看這篇文章:http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this

+0

很酷,馬修太太,這與我的想法是一致的。我們不幸的有幾千行代碼;誠實地說,它並不可怕 - 這個jQuery對象文字的包裝是最糟糕的部分。這將是一個合理的處理呢?把所有我們從選擇器捕獲到一個onReady中,然後將其他部分(ajax調用等)移動到不同的對象字面值,如obj.location_edit,obj.location_show ....我知道有點模糊,但寧願得到一些好的現在的建議,而不是稍後。 – timpone

+0

如果沒有看到所有代碼,有點難以說明,但我通常會盡可能少地將代碼放在文檔就緒函數中。就像你說的那樣,在文檔之外設置對象,然後在ready函數內部根據需要進行交互。如果你真的想要正確地做,你應該使用模塊重構:http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth –

+0

我也應該說你不需要甚至可以將您的選擇器放入文檔中。你只需從文檔內部調用你的對象或模塊,選擇器就可以正常工作。 –