Я отлаживаю плагин визуального композитора, который сломался после обновления Wordpress до 4.5, и я не могу понять, почему он бросает TypeError.
Сообщение об ошибке в консоли:
JQMIGRATE: Migrate is installed, version 1.4.0 load-scripts.php?....
Uncaught TypeError: $template.get is not a function composer-view.js?ver=4.1.1.1:73
Единственные вхождения $template
находятся в коде ниже. Я понимаю, что это не очень большой смысл, но, как я могу решить эту ошибку?
/**
* Convert html into correct element
* @param html
*/
html2element: function(html) {
var attributes = {},
$template;
if (_.isString(html)) {
this.template = _.template(html);
$template = $(this.template(this.model.toJSON()).trim());
} else {
this.template = html;
$template = html;
}
_.each($template.get(0).attributes, function(attr) { // **errors on this line**
attributes[attr.name] = attr.value;
});
this.$el.attr(attributes).html($template.html());
this.setContent();
this.renderContent();
},
Update:
Похоже, что это может быть проблемой с jQuery. Wordpress 4.5 включает jQuery 1.12, в котором исправлена ошибка, позволяющая запускать определенный код с неправильным синтаксисом. Я предполагаю, что код плагина должен иметь неправильный синтаксис, но до сих пор продолжался.
https://wordpress.org/support/topic/read-this-first-wordpress-45-master-list#post-8271654
Я смог решить проблему. Оказывается, я использовал более старую версию JS-композитора. Обновление к самой новой версии сломало мой сайт, поэтому я обнаружил ошибку и обновил функцию html2element
до
html2element: function(html) {
var $template, attributes = {},
template = html;
$template = $(template(this.model.toJSON()).trim()), _.each($template.get(0).attributes, function(attr) {
attributes[attr.name] = attr.value
}), this.$el.attr(attributes).html($template.html()), this.setContent(), this.renderContent()
},
Все снова хорошо работает для меня! Надеюсь, это поможет другим.
/wp-content/plugins/js_composer/assets/js/dist/backend.min.js
Я все еще получал эту ошибку после того, как попробовал патч в ответу Ben: Uncaught TypeError: не удается прочитать свойство "custom" из undefined
Итак, я изменил html2element в composer-view.js следующим образом:
html2element: function(html) {
var $template, attributes = {},
template = html;
$template = $(template(this.model.toJSON()).trim());
if($template.get(0))
{
_.each($template.get(0).attributes, function(attr) {
attributes[attr.name] = attr.value
})};
this.$el.attr(attributes).html($template.html()),
this.setContent(),
this.renderContent()
},
@Ben Это прекрасно работает!
Причина: Администратор не загружал правильный визуальный редактор для плагина js_composer после плагинов updatethis.
=============================================== ======
Ошибка:
Ошибка: TypeError: $template.get не является функцией Исходный файл: wp-content/plugins/js_composer_salient/assets/js/dist/backend.min.js? Ver = 4.10 Линия: 4047
=============================================== ======
Решение Перейти к файлу /wp -content/plugins/js_composer_salient/assets/js/dist/backend.min.js вокруг строки 4045:
====== > Заменить код ===================================== ================
html2element: function(html) {
var $template, attributes = {};
_.isString(html) ? (this.template = _.template(html), $template = $(this.template(this.model.toJSON(), vc.templateOptions["default"]).trim())) : (this.template = html, $template = html), _.each($template.get(0).attributes, function(attr) {
attributes[attr.name] = attr.value
}), this.$el.attr(attributes).html($template.html()), this.setContent(), this.renderContent()
},
====== > Заменить с помощью этого кода =================================== ====
html2element: function(html) {
var $template, attributes = {},
template = html;
$template = $(template(this.model.toJSON()).trim()), _.each($template.get(0).attributes, function(attr) {
attributes[attr.name] = attr.value}),
this.$el.attr(attributes).html($template.html()), this.setContent(),
this.renderContent()
},
Заметил, что код не передавался в функцию html2element, но существовал в функции, вызывающей его (render)
Следующий код полностью исправил мои проблемы, я могу загрузить страницу, добавить, клонировать, удалить и т.д.
render: function () {
var $shortcode_template_el = $( '#vc_shortcode-template-' + this.model.get( 'shortcode' ) );
if ( $shortcode_template_el.is( 'script' ) ) {
var newHtmlCode = _.template( $shortcode_template_el.html(),
this.model.toJSON(),
vc.templateOptions.default );
if(!_.isString(newHtmlCode)){
newHtmlCode = $shortcode_template_el.html();
}
this.html2element( newHtmlCode );
} else {
var params = this.model.get( 'params' );
$.ajax( {
type: 'POST',
url: window.ajaxurl,
data: {
action: 'wpb_get_element_backend_html',
data_element: this.model.get( 'shortcode' ),
data_width: _.isUndefined( params.width ) ? '1/1' : params.width,
_vcnonce: window.vcAdminNonce
},
dataType: 'html',
context: this
} ).done( function ( html ) {
this.html2element( html );
} );
}
this.model.view = this;
this.$controls_buttons = this.$el.find( '.vc_controls > :first' );
return this;
},
Я использую тему Applay (2.1.3, немного устаревшую). Я только что обновил WP и все плагины до последней версии (4.5.2) и пришел к этой проблеме. Я не анализировал поток этого компонента (js_composer), просто эту "сломанную" функцию (она не была нарушена). Я понял, что this.template и $template получают неправильные типы объектов (для него требуется другая проверка _.isString(html)
). Я решил это, добавив блок try и catch следующим образом:
ОРИГИНАЛ
html2element:function (html) {
var attributes = {},
$template;
if (_.isString(html)) {
this.template = _.template(html);
$template = $(this.template(this.model.toJSON()).trim());
} else {
this.template = html;
$template = html;
}
_.each($template.get(0).attributes, function (attr) {
attributes[attr.name] = attr.value;
});
this.$el.attr(attributes).html($template.html());
this.setContent();
this.renderContent();
},
ОБНОВЛЕНО
html2element:function (html) {
var attributes = {},
$template;
if (_.isString(html)) {
this.template = _.template(html);
} else {
try {
this.template = _.template(html());
} catch (err) {
this.template = html;
}
}
$template = $(this.template(this.model.toJSON()).trim());
_.each($template.get(0).attributes, function (attr) {
attributes[attr.name] = attr.value;
});
this.$el.attr(attributes).html($template.html());
this.setContent();
this.renderContent();
},
Оформление заказа под кодом для $template.get не является функцией и Uncaught TypeError: Невозможно прочитать атрибуты свойств undefined. Работал для меня.
html2element: function(html) {
var $template, attributes = {},
template = html;
$template = $(template(this.model.toJSON()).trim());
if($template.get(0))
{
_.each($template.get(0).attributes, function(attr) {
attributes[attr.name] = attr.value
})};
this.$el.attr(attributes).html($template.html()),
this.setContent(),
this.renderContent()
}
Ну, я нашел решение на этом сайте: https://wordpress.org/support/topic/visual-composer-is-not-working
сначала: отредактировать html2element:.... in in/wp-content/plugins/js_composer/assets/js/backend/composer-view.js
html2element: function(html) {
var $template, attributes = {},
template = html;
$template = $(template(this.model.toJSON()).trim()), _.each($template.get(0).attributes, function(attr) {
attributes[attr.name] = attr.value
}), this.$el.attr(attributes).html($template.html()), this.setContent(), this.renderContent()},
second: Однако, если вы откроете редактор frontend, у вас будет эта проблема с настройкой на custom_views.js: 101 и в строке 467 другого файла. Я забыл имя, но я думаю, что это может быть frontend_editor.js.
изменить в:\wp-content\plugins\js_composer\assets\js\frontend_editor\
Плохой код:
this.$controls = $( _.template( template, data, _.extend( {},
vc.template_options,
{ evaluate: /\{#([\s\S]+?)#}/g } ) ).trim() ).addClass( 'vc_controls' );
Фиксированный код:
this.$controls = $( _.template( template, data, _.extend( {},
vc.template_options,
{ evaluate: /\{#([\s\S]+?)#}/g } ) )().trim() ).addClass( 'vc_controls' );
Третий: см. черную магию.
Приветствия.
this.$controls = $(_.template(template, data, vc.template_options).trim()).addClass('vc_controls');
Я использую тему Astra. Это исправление работает на 99,9%. Для некоторых это только останавливает вращающееся колесо, но как только страница загружает визуальный композитор, нет.
Я немного изменил этот код (который теперь размещен повсюду)
Оригинальный код темы Astra здесь (composer-view.js)
html2element:function (html) {
var attributes = {},
$template;
if (_.isString(html)) {
this.template = _.template(html);
$template = $(this.template(this.model.toJSON()).trim());
} else {
this.template = html;
$template = html;
}
_.each($template.get(0).attributes, function (attr) {
attributes[attr.name] = attr.value;
});
this.$el.attr(attributes).html($template.html());
this.setContent();
this.renderContent();
},
Код, который работает:
html2element: function(html) {
var $template,
attributes = {},
template = html;
$template = $(template(this.model.toJSON()).trim()),
_.each($template.get(0).attributes, function(attr) {
attributes[attr.name] = attr.value
}); this.$el.attr(attributes).html($template.html()), this.setContent(), this.renderContent()
},
Основное отличие находится здесь (по сравнению с исходным кодом)
}); this.$el.attr
Вместо исходной запятой есть точка с запятой:):
}), this.$el.attr
Приветствия людей:) Итак
Я сделал эту модификацию, которая работает на моем WP 4.8.1 (PHP7)
в файле wp-content/plugins/js_composer/assets/js/backend/composer-view.js
вы должны изменить метод рендеринга:
замените эту строку
this.html2element(_.template($shortcode_template_el.html(), this.model.toJSON()));
этой строкой
this.html2element( $shortcode_template_el.html() );
Кажется, что функция _.template() не работает отлично и не возвращает хороший объект, поэтому лучше дать код html.
попробуйте обновить свою тему. Goto Appearance > Темы и проверьте наличие обновлений. Это автоматически разрешило проблему для меня после обновления.
Ошибка возникает, когда вы обновляете WP 4.5 для меня, запуская тему Nimva. Вы должны обновить до 2.02 Nimva, что позволяет автоматически обновлять.