原始的问题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对象内的方法。