原始的問題Javascript對象函數調用對象中的另一個功能,Rails的
想不通爲什麼我不能從第一函數中調用的第二功能。我正在使用jQuery-turbolinks。 (另外,如果你碰巧知道只在軌中運行頁面特定的JavaScript的更好的方法,請告訴我。目前,這是我最好的實現,在這裏我檢查身體是否有特定的類,如果它確實運行,那麼我運行這個JavaScript對象內的init函數)。
應用程序/資產/ Java腳本/ blogs.js
$(document).ready(function(){
var blogsjs = {
myBlog: this,
init: function(){
alert("hello from blogs");
$("input").on('click', function(){
$(this).hide('slow', function(){
myBlog.another();
});
});
},
another: function(){
alert("I was called!")
}
};
if($('body').hasClass("blogs") == true){
blogsjs.init();
}
});
解決方案之後從一個方法內反饋
只是簡單地使用object.method()
語法來調用同一對象中的另一種方法:
$(document).ready(function(){
var blogsjs = {
init: function(){
alert("hello from blogs");
$("input").on('click', function(){
$(this).hide('slow', function(){
blogsjs.another();
});
});
},
another: function(){
alert("I was called!");
blogsjs.yetanother();
},
yetanother: function(){
alert("yet another called");
}
};
blogsjs.init();
});
我不喜歡這段代碼看起來有多混亂,但是我認爲,面向對象設計的封裝優勢是可靠的:每個資源的javascript只能訪問其javascript對象內的方法。