Mil*_*rov 14 javascript magento magento-1.6
最后几天,由于一些客户抱怨并与我们的营销人员讨论,我已经请求更改可配置产品选项的默认行为.他们要求我从选项下拉菜单中删除+ $ xx.xx,因为它会让客户/访客感到困惑,只留下可用选项而不显示价格变化.从他们的观点来看还算公平,但从开发人员的角度来看,我认为这有点棘手.该站点正在运行Magento CE 1.6.2,我们需要覆盖/更改的文件是/public_html/js/varien/configurable.js.我们需要更改其中的getOptionLabel函数,以便它不显示价格变化.所以我的问题是:什么是正确的Magento方式来更改此文件而不是触摸核心javascript文件?提前致谢.
Ant*_*n S 30
从原型手册http://prototypejs.org/doc/latest/language/Function/prototype/wrap/看到这个,你可以包装任何对象方法,如果需要甚至可以调用"parent",这里是一个伪样本:
//where Product.Config is the object/class you need to "override"
Product.Config.prototype.getOptionLabel = Product.Config.prototype.getOptionLabel.wrap(function(parentMethod){
//replace the original method here with your own stuff
//or call parentMethod(); if conditions don't match
});
Run Code Online (Sandbox Code Playgroud)
Vin*_*nai 26
只是为了添加@ anton-s绝对正确的答案,你也可以做"完整"类重写:
// Create the original class
var ClassA = Class.create();
ClassA.prototype = {
initialize: function(config) {
this.config = config;
},
test: function(msg) {
console.log('Hi from class A with message ' + msg);
}
};
// Create new class extending the original class
var ClassB = Class.create(ClassA, {
// $super is a reference to the original method
test: function($super, msg) {
console.log('Hi from class B');
console.log('this.config is accessible in class B: ' + this.config);
$super(msg + ' ...')
}
});
// To make the extend an override, you can do this:
ClassA = ClassB;
// ClassA now is ClassB overriding the original ClassA
var a = new ClassA('some config data');
a.test('Call A 1');
Run Code Online (Sandbox Code Playgroud)
因为所有这些只适用于原型类,而不是已经实例化的对象,我也会抛出这个hack,这几乎也是wrap()的作用:
// Overriding a method of an already instantiated object
// There are many ways to do this more elegantly thanks to the amazing JS scoping magic
a.origTest = a.test;
a.test = function(msg) {
console.log('Hi from the patched method');
this.origTest(msg);
}
a.test('Call A 2');
Run Code Online (Sandbox Code Playgroud)
请记住,该wrap()方法更好,也可以用于类定义或具体实例.
// Wrap method of concrete instance
spConfig.getOptionLabel = spConfig.getOptionLabel.wrap(function(parentMethod, option, price) {
return parentMethod(option, price);
});
// Wrap method of class declaration
Product.Config.prototype.getOptionLabel = Product.Config.prototype.getOptionLabel.wrap(function(parentMethod, option, price) {
return parentMethod(option, price);
});
Run Code Online (Sandbox Code Playgroud)