제품의 카테고리와 하위 카테고리를 나열해야하는 앱을 만들고 있습니다.Deferred 오브젝트를 사용하는 올바른 방법입니까?
사용자가 카테고리를 선택하면이 카테고리와 관련된 하위 카테고리가 서버에서 아약스로로드되지만 나중에로드되지 않은 경우에만 (이 경우 DOM에서로드됩니다).
코드 : 코드가 여기 저기 콜백의 전체지고 있었기 때문에, 나는 jQuery를 이연 객체를 사용하기로 결정하지만,이는 경우 나도 몰라 http://jsbin.com/abijad/edit#javascript,html
var $form = $('#new-product-form');
$form.on('change', 'select.product-categories', function(e) { //I'm using event delegation for a future feature...
getSubCategories($(this).val()).done(function($subCategoriesEl){
$form.find('select.product-subcategories').not($subCategoriesEl).hide();
$subCategoriesEl.show();
});
});
var getSubCategories = function(categoryId) {
var dfd = $.Deferred(),
$alreadyisLoaded = $form.find('select.product-subcategories').map(function(idx, el){
if(parseInt($(this).data('category'), 10) === parseInt(categoryId, 10)){
return el;
}
});
if($alreadyisLoaded.length > 0){ //don't request subCategories that already are loaded
console.log('SubCategory loaded from DOM');
dfd.resolve($alreadyisLoaded);
} else {
var subCategoriesHtml = '<select data-category="' + categoryId + '" class="product-subcategories">';
$.get('/', { //The ajax request will only be simulated
categoryId : categoryId
}, function (result) {
//simulate success :X
result = {"status":1,"data":[{"name":"Sub-Category I","id":1},{"name":"Sub-Category II","id":2},{"name":"Sub-Category III","id":3}]};
console.log('SubCategory loaded with Ajax');
if(result.status === 1) { //Success
for(var subCategoryInfo in result.data) {
if(result.data.hasOwnProperty(subCategoryInfo)){
subCategoriesHtml += '<option value="' + result.data[subCategoryInfo].id + '">';
subCategoriesHtml += result.data[subCategoryInfo].name + '</option>';
}
}
subCategoriesHtml += '</select>';
var $subCategories = $(subCategoriesHtml).hide().appendTo($form);
dfd.resolve($subCategories);
} else {
dfd.reject();
}
});
}
return dfd.promise();
};
<form id="new-product-form">
<select class="product-categories">
<option value="1">Category I</option>
<option value="2">Category II</option>
<option value="3">Category III</option>
<option value="4">Category IV</option>
<option value="5">Category V</option>
</select>
<select data-category="1" class="product-subcategories">
<option value="1">SubCategory I</option>
<option value="2">SubCategory II</option>
<option value="3">SubCategory III</option>
<option value="4">SubCategory IV</option>
<option value="5">SubCategory V</option>
</select>
</form>
올바른 구현. 누군가 내가 옳은 일을했다고 말해도 될까요, 아니면 다르게해야합니까?
링크와 함께 질문에 관련 코드를 적어주십시오. 목표는 SO를 가능한 한 자급 자족하도록 유지하는 것입니다. 외부 사이트가 사라지더라도 문제는 여전히 관련성이 있어야합니다. –
@JamesMontagne 편집을 참조하십시오. – JCM
난 그냥 지연된 개체를 캐싱하고 결국 큰 범주/하위 범주 상황에서 숨겨진 요소의 큰 숫자를 피하기 위해 각 후속 변경 옵션을 다시 작성했을 것입니다,하지만 그 외에, 당신은 무엇을 가지고 작동합니다 요소의 수가 너무 커지지 않는 한 오래. –