Trigger event in jQuery with params - javascript

I am using the django-autocomplete-light library to have a ModelSelect2 field in my form. I need to externally change the currently selected item. The library has a following code to handle the select2:selecting event.
document.addEventListener('dal-init-function', function () {
...
yl.registerFunction( 'select2', function ($, element) {
$element.on('select2:selecting', function (e) {
var data = e.params.args.data;
if (data.create_id !== true)
return;
e.preventDefault();
...
I have developed the following line to trigger the event:
params = {
"params": {
"args": {
"data": {
id: "324856",
selected_text: "ABERTAMY (Karlovy Vary)",
text: "ABERTAMY (Karlovy Vary)"
}
}
}
};
$( "#id_hlavni_katastr" ).trigger( "select2:selecting", params )
However, the params are not passed and I have searched the whole e variable without finding the data. How to update the trigger event so it passes on the params correctly.

Instead of $element.on('select2:selecting', function (e) { ... }, you can replace it with $element.on('select2:selecting', function (e, customParrams) { ... }. The parameters you passed when using the trigger method will be populated in the customParrams variable. Here's an example:
$('input').on('click', function (e, customParams) {
console.log(customParams.params.args.data);
});
var params = {
"params": {
"args": {
"data": {
id: "324856",
selected_text: "ABERTAMY (Karlovy Vary)",
text: "ABERTAMY (Karlovy Vary)"
}
}
}
};
$('input').trigger('click', params);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden">
For more examples you can visit the jQuery documentation on the following page.

Related

JS works with .include but fails with .extend

I made this JS to add a functionality on a form (backend) that computes a field when the event click is triggered. So far the code recomputes when I use ".include" but the whole JS in all views fail since I'm using ".include". When I try to use extend my code does nothing. Looks like Odoo doesn't add the extended code to the JS engine so my question is, what am I doing wrong here? Is there something else I need to add so my code works as extended?
odoo.define('med_care.TestRenderer', function (require) {
"use strict";
var viewRegistry = require('web.view_registry');
var FormRenderer = require('web.FormRenderer');
var FormView = require('web.FormView');
var TestFormRenderer = FormRenderer.extend({
events: _.extend({}, FormRenderer.prototype.events, {
'click .sign_selector': '_onSignSelectorClicked',
}),
init: function (parent, state, params) {
this._super.apply(this, arguments);
this.fields = state.fields;
this._onSignSelectorClicked = _.debounce(this._onSignSelectorClicked, 300, true);
},
confirmChange: function (state, id, fields, e) {
var self = this;
if (state.model == 'med.test') {
return this._super.apply(this, arguments).then(function () {
self.canBeSaved(self.state.id);
});
}
},
_onSignSelectorClicked: function (event) {
this.state.data.telephone = '333';
if (this.state.model == 'med.test') {
var info_test = {
dataPointID: this.state.id,
changes: {telephone: '333'},
viewType: "form",
notifyChange: true
};
var odoo_event = this.trigger_up('field_changed', info_test);
this.confirmChange(this.state, this.state.id, "telephone",
odoo_event)
}
},
});
var TestFormView = FormView.extend({
config: _.extend({}, FormView.prototype.config, {
Renderer: TestFormRenderer,
}),
});
viewRegistry.add('test_form', TestFormView);
return TestFormView;
});

Jquery contextMenu title and function on submenu

I'm creting a jquery context menu, using https://swisnl.github.io/jQuery-contextMenu/ .
I've sucessfully done the creation part of the submenu.
I had to use build, in order to have some data that is only available on runtime.
This data appears on a submenu, and I need to have a title on each of those submenu items, as well as click funtion on each of them.
I cant seem to make it work, both the title and the function on those submenu items.
Here is my code:
$.contextMenu({
selector: '.gridRelatorioCursorMorada',
build: function ($triggerElement, e) {
var coords = $triggerElement[0].attributes['data-coord'].nodeValue;
var coordsArray = coords.split(',');
return {
callback: function (key) {
if (key === 'get') {
getdata();
}
},
items: {
get: {
name: "Get data"
},
see: {
name: "See data",
items: {
normal: { name: coords },
graus: { name: dd2dms(coordsArray[0], coordsArray[1]) },
siresp: { name: decimalToSIRESPCoordinates(coordsArray[0], coordsArray[1]) }
}
}
}
};
}
});
Since the events part of contextMenu doesnt work with build, I dont know what else to do.
I've also added the following code:
$(document).on('contextmenu', function () {
$('.context-menu-submenu > ul > li').attr('title', 'tituro');
});
But it also doesnt work.
My mistake.
Event does work on build.
This got me to get the title on each of the submenu items.
The click function I got it working with the callback function.

Add an "All" item to kendo ui listview populated by a remote datasource

I am building a website using MVC 4, Web API, and Kendo UI controls.
On my page I am using a Kendo UI Listview to filter my grid. I'm trying to add an "ALL" option as the first item in my listview.
Here is the listview:
var jobsfilter = $("#jobfilter").kendoListView({
selectable: "single",
loadOnDemand: false,
template: "<div class='pointercursor' id=${FilterId}>${FilterName}</div>",
dataSource: filterDataSource,
change: function (e) {
var itm = this.select().index(), dataItem = this.dataSource.view()[itm];
if (dataItem.FilterId !== 0) {
var $filter = new Array();
$filter.push({ field: "JobStatusId", operator: "eq", value: dataItem.FilterId });
jgrid.dataSource.filter($filter);
} else {
jgrid.dataSource.filter({});
}
}
});
Here is my datasource:
var filterDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "api/Filter"
}
},
schema: {
model: { id: "FilterId" }
}
});
I have tried a few different methods to make this happen:
I can make it work if I attach it to a button - but I need it there
when the data loads.
If I add it to the dataBound event of the listview, it causes the
databound event to go into a loop and adds the item a bunch (IE) or kills the browser (firefox). Adding preventDefault did nothing.
I've read up on adding a function to the Read paramter of the
datasource, but I think that is simply not the correct place to do
it.
Based on what I've read, I think that I should be able to do it in the dataBound event of the listview and that my implementation is incorrect. Here is the listview with dataBound event added that crashes my browser (Firefox) - or adds about 50 "All" items to the listview (IE).
var jobsfilter = $("#jobfilter").kendoListView({
selectable: "single",
loadOnDemand: false,
template: "<div class='pointercursor' id=${FilterId}>${FilterName}</div>",
dataSource: {
transport: {
read: {
url: "api/Filter"
}
}
},
dataBound: function (e) {
var dsource = $("#jobfilter").data("kendoListView").dataSource;
dsource.insert(0, { FilterId: 0, FilterName: "All" });
e.preventDefault();
},
change: function (e) {
var itm = this.select().index(), dataItem = this.dataSource.view()[itm];
if (dataItem.FilterId !== 0) {
var $filter = new Array();
$filter.push({ field: "JobStatusId", operator: "eq", value: dataItem.FilterId });
jgrid.dataSource.filter($filter);
} else {
jgrid.dataSource.filter({});
}
}
});
Any help would be greatly appreciated.
Why don't you add it server-side?
Anyway, if you want to do it in dataBound, just check whether it exists and only add if it doesn't:
dataBound: function (e) {
var dsource = this.dataSource;
if (dsource.at(0).FilterName !== "All") {
dsource.insert(0, {
FilterId: 0,
FilterName: "All"
});
}
},
As an explanation to the problem you're seeing: you're creating an infinite loop since inserting an element in the data source will trigger the change event and the list view will refresh and bind again (and thus trigger dataBound).
You could also encapsulate this in a custom widget:
(function ($, kendo) {
var ui = kendo.ui,
ListView = ui.ListView;
var CustomListView = ListView.extend({
init: function (element, options) {
// base call to widget initialization
ListView.fn.init.call(this, element, options);
this.dataSource.insert(0, {
FilterId: 0,
FilterName: "All"
});
},
options: {
name: "CustomListView"
}
});
ui.plugin(CustomListView);
})(window.jQuery, window.kendo);

Trigger event from an approuter

I created an application and it worked fine, most of the functionality is just the application reacting to different events. I would like to implement a router so that users would be able to show their search results with other users etc. The problem is the router appears to be set up correctly, as when i use it to append things directly to the body everything works as expected. When I try to use the router to trigger events though nothing happens, any help would be greatly appreciated. It is worth mentioning I suppose that this is not the complete code but just the parts that seemed relevant to the issue I am experiencing.
IEG = new Backbone.Marionette.Application();
IEG.addRegions({
searchBox: '#searchBox',
resultBox: '#resultBox',
modalBox: '#modalBox',
recipientBox: '#recipientBox',
confirmBox: '#confirmToggleActive'
});
IEG.vent = _.extend({}, Backbone.Events);
IEG.Router = Backbone.Marionette.AppRouter.extend({
routes: {
'': 'index'
},
index: function () {
IEG.vent.trigger("default"); ////TRIGGER EVENT DOES NOT WORK
//$(document.body).append("Index route has been called..");
}
});
SearchBoxView = Backbone.Marionette.ItemView.extend({
template: Handlebars.templates['search'],
events: {
'click #addGroup': 'addGroup',
'keyup #searchStr': 'evaluateSearch'
},
addGroup: function () {
IEG.vent.trigger("addGroup");
},
clearValidationMsg: function () {
$('#searchErrors').html("");
},
evaluateSearch: function (e) {
console.log("keyup DO SOMETHING> ", e.keyCode);
if (e.keyCode === 13) {///press enter execute search
var searchStr = $('#searchStr').val().trim();
if (searchStr) {
IEG.vent.trigger("searchGroups", searchStr);
}
}
else if (e.keyCode === 8 || e.keyCode === 46) {//backspace and delete keys
var searchStr = $('#searchStr').val().trim();
if (!searchStr) {//when searchbar is cleared show all groups
IEG.vent.trigger("searchGroups", null)
}
}
},
validateEmail: function (searchStr) {
return /^.+#.+\..+$/.test(address);
}
});
$(document).ready(function () {
IEG.start();
new IEG.Router;
Backbone.history.start();
IEG.vent.on("default", function () {
var SBV = new SearchBoxView();
IEG.searchBox.show(SBV);
IEG.searchColl = new GroupEntries();
IEG.searchColl.fetch({
data: {
cmd: 0, //search groups
searchStr: null //if null show all groups
},
success: function (data) {
searchResults = new SearchResultsView({ collection: IEG.searchColl });
IEG.resultBox.show(searchResults);
}
});
});
});
Make sure your event listeners are defined before the event is triggered. Most likely, the event trigger is working fine, but your event listener is registered after the router has triggered the event and nothing happens...

Deletion on the ajax callback issue

I have a dashboard in my website which contain some entries in table, each entry in the table have a delete button. When user click over the delete button a Ajax call happens and I am deleting that entry in the callback function. My code :
$(".del").live({
click: function () {
$.post("/Home/DeleteTemplate", {
name: $(this).parent().siblings("td:first").children("a").html()
}, function (data) {
$(this).parents("tr").remove(); //Inside the callback
});
}
});
Now my problem is that if I was deleting the row in the callback function the row was not removed from the entries immediately. I have to close and open the dashboard again to see the result.
But if I delete the entry outside of the callback function then it removed at the same time:
$(".del").live({
click: function () {
$.post("/Home/DeleteTemplate", {
name: $(this).parent().siblings("td:first").children("a").html()
});
$(this).parents("tr").remove(); //Outside the callback
}
});
What's the problem here?
this does not refer to your selector inside callback, do this:
$(".del").live({ click: function () {
var that = $(this); // added this
$.post("/Home/DeleteTemplate",
{ name: that.parent().siblings("td:first").children("a").html() },
function (data) {
that.parents("tr").remove(); // used "that" here
});
}
});

Categories

Resources