На самом деле не связано с конкретным вопросом, но связано с получением null
на findFragmentById
, если вы вызываете findFragmentById
сразу после коммита, он вернет ноль или последний фрагмент (перед коммитом), причина в том, что коммит делать асинхронно запрос.
Из документов:
Планирует фиксацию этой транзакции. Фиксация происходит не сразу; это будет запланировано как работа над основным потоком, которая будет сделана в следующий раз, когда поток будет готов.
Если вам нужно немедленно findFragmentById
, например, изменить цвет текста строки состояния после добавления фрагмента, позвоните executePendingTransactions()
после commit()
getSupportFragmentManager().executePendingTransactions();
//call findFragmentById
There are two things that can make your event binding code slow: the selector and the # of bindings. The most critical of the two is the # of bindings, but the selector could impact your initial performance.
As far as selectors go, just make sure you don't use pure class name selectors like As far as the amount of bindings: if you have a relatively medium-sized amount of elements then you should be fine - anything up to 200, 300 potential element matches will perform fine in modern browsers. If you have more than this you might want to instead look into Event Delegation. What is Event Delegation? Essentially, when you run code like this: jQuery is doing something like this behind the scenes (binding an event for each matched element): This can get inefficient if you have a large amount of elements. With event delegation, you can cut down the amount of bindings done down to one. But how? The event object has a Thankfully you don't actually have to code the above with jQuery. The live function, which is advertised as an easy way to bind events to elements that do not yet exist, is actually able to do this by using event delegation and checking at the time an action occurs if the target matches the selector you specify to it. This has the side effect, of course, of being very handy when speed is important. The moral of the story? If you are concerned about the amount of bindings your script has just replace Do note, however, that not all events are supported by .myclass
. If you know that the class of myclass
will always be in a div.myclass
as it will help jQuery find the matching elements faster. Also, don't take advantange of jQuery letting you give it huge selector strings. Everything it can do with string selectors it can also do through functions, and this is intentional, as it is (marginally, admittedly) faster to do it this way as jQuery doesn't have to sit around to parse your string to figure out what you want. So instead of doing $('#myform input:eq(2)');
you might do $('input','#myform').eq(2);
. By specifying a context, we are also not making jQuery look anywhere it doesn't have to, which is much faster. More on this here.
$('div.test').click(function() {
doSomething($(this));
});
$('div.test').each(function() {
this.addEventListener('click', function() {
doSomething(this);
}, false);
});
target
property that lets you know what element the event acted on. So you could then do something like this:$(document).click(function(e) {
var $target = $(e.target);
if($target.is('div.test')) { // the element clicked on is a DIV
// with a class of test
doSomething($target);
}
});
.bind
with .live
and make sure you have smart selectors..live
. If you need something not supported by it, you can check out the livequery plugin, which is live on steroids.
В принципе, лучше вы не добьетесь. Все, что он делает, - это вызывает attachEventListener () для каждого из выбранных вами элементов.
Если рассматривать только время синтаксического анализа, этот метод, вероятно, быстрее, чем установка встроенных обработчиков событий для каждого элемента.
В общем, я бы счел это очень недорогая операция.