Mithriljs does not update DOM on change in data - mithril.js

I read somewhere, the DOM is updated every time an event occurs and there is changes in data which are bound to DOM. So I wished to learn more about it. I tried the code below but the DOM is not updated when data in textarea changes but its updated whenever I click or press tab key.
var app = {
controller: function () {
var self = this;
this.model = {};
this.model.errors = [];
this.break_data = function (value) {
self.model.errors = value.split(' ');
m.redraw();
}
},
view: function (ctrl) {
return m('.content', [
m('textarea', {onchange: m.withAttr('value', ctrl.break_data)}),
ctrl.model.errors.map(function (error) {
return m('.error', error);
})
]);
}
}
m.mount(document.getElementById('app'), app);
I even tried m.startComputaion(), m.stopComputation() and m.redraw() non of them works.

The redrawing timing is described here: https://stackoverflow.com/a/30728976/70894
As for your example, the problem is not Mithril but the event. You need to use oninput instead of onchange to look for immediate changes. As the Mozilla docs for the "change" event states:
The change event is fired for input, select, and textarea
elements when a change to the element's value is committed by the
user. Unlike the input event, the change event is not necessarily
fired for each change to an element's value.
Here's a fiddle with your code that uses oninput: http://jsfiddle.net/ciscoheat/LuLcra77/
Note that you don't need m.redraw in the event handler anymore now when the correct event is used, since Mithril redraws automatically after every event defined in a call to m().

Related

How to prevent #change event when changing v-model value

I'm building an auto-complete menu in Vue.js backed by Firebase (using vue-fire). The aim is to start typing a user's display name and having match records show up in the list of divs below.
The template looks like this:
<b-form-input id="toUser"
type="text"
v-model="selectedTo"
#change="searcher">
</b-form-input>
<div v-on:click="selectToUser(user)" class="userSearchDropDownResult" v-for="user in searchResult" v-if="showSearcherDropdown">{{ user.name }}</div>
Upon clicking a potential match the intention is to set the value of the field and clear away the list of matches.
Here is the code portion of the component:
computed: {
/* method borrowed from Reddit user imGnarly: https://www.reddit.com/r/vuejs/comments/63w65c/client_side_autocomplete_search_with_vuejs/ */
searcher() {
let self = this;
let holder = [];
let rx = new RegExp(this.selectedTo, 'i');
this.users.forEach(function (val, key) {
if (rx.test(val.name) || rx.test(val.email)) {
let obj = {}
obj = val;
holder.push(obj);
} else {
self.searchResult = 'No matches found';
}
})
this.searchResult = holder;
return this.selectedTo;
},
showSearcherDropdown() {
if(this.searchResult == null) return false;
if(this.selectedTo === '') return false;
return true;
}
},
methods: {
selectToUser: function( user ) {
this.newMessage.to = user['.key'];
this.selectedTo = user.name;
this.searchResult = null;
}
}
Typeahead works well, on each change to the input field the searcher() function is called and populates the searchResult with the correct values. The v-for works and a list of divs is shown.
Upon clicking a div, I call selectToUser( user ). This correctly reports details from the user object to the console.
However, on first click I get an exception in the console and the divs don't clear away (I expect them to disappear because I'm setting searchResults to null).
[Vue warn]: Error in event handler for "change": "TypeError: fns.apply is not a function"
found in
---> <BFormInput>
<BFormGroup>
<BTab>
TypeError: fns.apply is not a function
at VueComponent.invoker (vue.esm.js?efeb:2004)
at VueComponent.Vue.$emit (vue.esm.js?efeb:2515)
at VueComponent.onChange (form-input.js?1465:138)
at boundFn (vue.esm.js?efeb:190)
at invoker (vue.esm.js?efeb:2004)
at HTMLInputElement.fn._withTask.fn._withTask (vue.esm.js?efeb:1802)
If I click the div a second time then there's no error, the input value is set and the divs disappear.
So I suspect that writing a value to this.selectedTo (which is also the v-model object for the element is triggering a #change event. On the second click the value of doesn't actually change because it's already set, so no call to searcher() and no error.
I've noticed this also happens if the element loses focus.
Question: how to prevent an #change event when changing v-model value via a method?
(other info: according to package.json I'm on vue 2.5.2)
On:
<b-form-input id="toUser"
type="text"
v-model="selectedTo"
#change="searcher">
The "searcher" should be a method. A method that will be called whenever that b-component issues a change event.
But looking at your code, it is not a method, but a computed:
computed: {
searcher() {
...
},
showSearcherDropdown() {
...
}
},
methods: {
selectToUser: function( user ) {
...
}
}
So when the change event happens, it tries to call something that is not a method (or, in other words, it tries to call a method that doesn't exist). That's why you get the error.
Now, since what you actually want is to update searcher whenever this.selectedTo changes, to get that, it is actually not needed to have that #change handler. This is due to the code of computed: { searcher() { already depending on this.selectedTo. Whenever this.selectedTo changes, Vue will calculate searcher again.
Solution: simply remove #change="searcher" from b-form. Everything else will work.
#acdcjunior, thanks for your answer.
Of course just removing the reference to searcher() just means no action is taken upon field value change so the field won’t work at all.
Moving the searcher() function into methods: {} instead of computed: {} means that it will be called on an input event and not a change even (another mystery but not one for today). A subtle difference that takes away the typeahead feature I’m aiming at.
However, it did make me remember that the result of computed: {} functions are cached and will be re-computed when any parameters change. In this case I realised that the searcher() function is dependent upon the this.selectedTo variable. So when the selectToUser() function sets this.selectedTo it triggers another call to searcher().
Fixed now. In case anyone has a similar problem in the future, I resolved this by turning to old fashioned semaphore by adding another variable.
var userMadeSelection: false
Now, searcher() begins with a check for this scenario:
computed: {
searcher() {
if(this.userMadeSelection) {
this.userMadeSelection = false;
return this.selectedTo;
}
…
and then in selectToUser():
this.userMadeSelection = true;

Can I loop through fullcalendar events after loading calendar?

My fullcalendar object has events loaded from a URL as seen below. When an event on the calendar is clicked, I need to not only pass that event back to a function (which is built in), but I need to also find another event that is associated with the clicked event by a field called lesson_id). Is there a way to loop through the events to find the other event with the same lesson_id?
events: {
url: smurl + "&subCmd=sch",
error: function () {
$('#script-warning').show();
},
viewRender: function (view) {
try {
setTimeline(view);
} catch (err) { }
}
},
I believe I have found my answer. It appears that .fullCalendar( 'clientEvents' [, idOrFilter ] ) returns an array of event objects held in memory.

How do I determine open/closed state of a dijit dropdownbutton?

I'm using a dijit DropDownButton with an application I'm developing. As you know, if you click on the button once, a menu appears. Click again and it disappears. I can't seem to find this in the API documentation but is there a property I can read to tell me whether or not my DropDownButton is currently open or closed?
I'm trying to use a dojo.connect listener on the DropDownButton's OnClick event in order to perform another task, but only if the DropDownButton is clicked "closed."
THANK YOU!
Steve
I had a similar problem. I couldn't find such a property either, so I ended up adding a custom property dropDownIsOpen and overriding openDropDown() and closeDropDown() to update its value, like this:
myButton.dropDownIsOpen = false;
myButton.openDropDown = function () {
this.dropDownIsOpen = true;
this.inherited("openDropDown", arguments);
};
myButton.closeDropDown = function () {
this.dropDownIsOpen = false;
this.inherited("closeDropDown", arguments);
};
You may track it through its CSS classes. When the DropDown is open, the underlying DOM node that gets the focus (property focusNode) receives an additional class, dijitHasDropDownOpen. So, for your situation:
// assuming "d" is a dijit.DropDownButton
dojo.connect(d, 'onClick', function() {
if (dojo.hasClass(d.focusNode, 'dijitHasDropDownOpen') === false) {
performAnotherTask(); // this fires only if the menu is closed.
}
});
This example is for dojo 1.6.2, since you didn't specify your version. It can, of course, be converted easily for other versions.

Which events are attached to an element?

How can I receive all events attached to an element with dojo?
dojo.query('#mydiv') // which events does #mydiv has?
To get all events on a DOM element:
// Get my div
myDiv = dojo.byId("myDiv");
// Obtain all event-related attributes
var events = dojo.filter(
myDiv.attributes,
function(item) {
return item.name.substr(0, 2) == 'on';
}
);
// Execute first found event, just for fun
eval(events[0].value);
If you get myDiv using dojo.query, remember that dojo.query returns an array, so your element would be in myDiv[0].
This solution does not work with events attached with dojo.connect. There probably is a way to extract this info from Dojo inner workings, but you would have to delve into the source code to understand how.
Another option is that you explicitly manage all dojo.connect events with a global registry. You could use dojox.collections to make this easier. For example, creating a global registry whose keys will be the dom nodes, and values will be the handles returned by dojo.connect (these handles contain the dom node, the type of event and the function to execute):
// On startup
dojo.require(dojox.collections.Dictionary);
eventRegistry = new dojox.collections.Dictionary();
...
// Registering an event for dom node with id=myDiv
var handle1 = dojo.connect(dojo.byId("myDiv"), "onclick", null, "clickHandler");
// Check if event container (e.g. an array) for this dom node is already created
var domNode = handle1[0];
if (!eventRegistry.containsKey(domNode))
eventRegistry.add(domNode, new Array());
eventRegistry.item(domNode).push(handle1);
...
// Add another event later to myDiv, assume container (array) is already created
var handle2 = dojo.connect(dojo.byId("myDiv"), "onmouseover", null, "mouseHandler");
eventRegistry.item(domNode).push(handle2);
...
// Later get all events attached to myDiv, and print event names
allEvents = eventRegistry.item(domNode);
dojo.forEach(
allEvents,
function(item) {
console.log(item[1]);
// Item is the handler returned by dojo.connect, item[1] is the name of the event!
}
);
You can hide the annoying check to see if event container is already created by creating a subclass of dojox.collections.Dictionary with this check already incorporated. Create a js file with this path fakenmc/EventRegistry.js, and put it beside dojo, dojox, etc:
dojo.provide('fakenmc.EventRegistry');
dojo.require('dojox.collections.Dictionary');
dojo.declare('fakenmc.EventRegistry', dojox.collections.Dictionary, {
addEventToNode : function(djConnHandle) {
domNode = djConnHandle[0];
if (!this.containsKey(domNode))
this.add(domNode, new Array());
this.item(domNode).push(djConnHandle);
}
});
Using the above class you would have to dojo.require('fakenmc.EventRegistry') instead of 'dojox.collections.Dictionary', and would simply directly add the dojo connect handle without other checks:
dojo.provide('fakenmc.EventRegistry');
eventRegistry = new fakenmc.EventRegistry();
var handle = dojo.connect(dojo.byId("myDiv"), "onclick", null, "clickHandler");
eventRegistry.addEventToNode(handle);
...
// Get all events attached to node
var allEvents = eventRegistry.item(dojo.byId("myDiv"));
...
This code is not tested, but I think you get the idea.
If its only for debugging purpose. You can try dijit.byId("myId").onClick.toString(); in your firebug console and you can see the entire onclick code this works even if the function is anonymous you can view the content of anonymous content.

jQuery - Page with a ton of checkboxes, how to bind?

I have a page of checkboxes, in some cases more than 100. I'm currently doing this:
$('form[name=myForm] input[name=myCheckbox]').change(function(){
var numChkd = $('input[name=myCheckbox]:checked').size();
console.log(numChkd);
};
But as you could imagine this can get wicked slow. Is there a better way to bind an event to multiple elements? This works, but I want to know if there is a better way?
You can bind an event to the parent container that will wrap all of the checkboxes and then check if the object that caused an event is a checkbox. This way you only bind one event handler. In jQuery you can use $.live event for this.
Don't recount every time a checkbox changes. Just use a global variable, like this:
var CheckboxesTicked = 0;
$(document).ready(function() {
CheckboxesTicked = $(":checkbox:checked").length;
$(":checkbox").change(function() {
if ($(this).is(":checked")) {
CheckboxesTicked += 1
} else {
CheckboxesTicked -= 1
}
});
});
Btw, the documentation states that you'd better use .length instead of .size() performance wise.
You could create a container element (like a Div with no styling) and attach the event handler to the container. That way, when the change() event happens on one of the checkboxes and percolates up the DOM, you'll catch it at the container level. That's one way to make this faster.
You should use .delegate(). One binding on a parent element can replace all the individual bindings on the child elements. It's perfect for this situation (and also solves the problem of attaching behavior to dynamically-added elements, should the need arise).
$('form[name=myForm]').delegate('input[name=myCheckbox]','change', function(){
var numChkd = $(this).siblings(':checked').length; // assuming siblings
console.log(numChkd);
});
This is how I would approach it:
$('form[name=myForm]').each(function() {
var $form = $(this),
$boxes = $form.find('input[name=myCheckbox]');
$form.delegate('input[name=myCheckbox]', 'change', function() {
var numChkd = $boxes.filter(':checked').length;
console.log(numChkd);
});
});
This takes advantage of caching the $boxes selection. It will look for all the boxes when it sets up the event. It uses .delegate() to attach an event to the form which will get fired anytime an child input[name=myCheckbox] creates a change event. In this event handler, you can easily filter the already obtained list of checkboxes by which ones are :checked and get the length of the matched elements. (The documentation for .size() basically states there is no reason to ever use it... It just returns this.length anyway...)
See this fiddle for a working demo
demo: http://jsfiddle.net/kKUdm/
$(':checkbox').change(function(){
if($(this).is(':checked')){
var name = $(this).attr('name');
var value = $(this).val();
console.log(name + ':' + value);
}
});
Var $chks = $(":checkbox");
Var ChkCount =0;
Var chktimer =0;
Function updateChkCount(){
ChkCount = $chks.filter(":checked").length;
$chks.end();
// do something witb ChkCount
}
$chks.bind("check change", function(){
clearInterval(chktimer);
chktimer = setInterval("updateChkCount()",250);
});