将常见逻辑提取到JavaScript中的可重用函数 [英] Extracting common logic to a reusable function in JavaScript

查看:77
本文介绍了将常见逻辑提取到JavaScript中的可重用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我有:

$(function(){
  $("a[data-toggle-description-length]='toggle'").click(function(event){
    // common part:
    event.preventDefault();
    $("span.show_hide").toggleClass("shown hidden");
    $("table").toggleClass("wide narrow");
    $.get('/toggle_full_details');
  }); 
});

$(function(){
  $("a[data-toggle-description-length-refocus]='toggle'").click(function(event){
    event.preventdefault();
    $("span.show_hide").toggleClass("shown hidden");
    $("table").toggleclass("wide narrow");
    $("input[type='text']:first").focus();   // focus
    $.get('/toggle_full_details');
  }); 
});

如何将通用逻辑提取到函数中?

How can I extract the common logic to a function?

我尝试过:

$(function update-ui(event){
    event.preventdefault();
    $("span.show_hide").toggleClass("shown hidden");
    $("table").toggleclass("wide narrow");
});

并使用以下代码对其进行调用:

And called it using the following code:

$(function(){
  $("a[data-toggle-description-length]='toggle'").click(function(event){
    update-ui(event);
    $.get('/toggle_full_details');
  }); 
});

但是我得到了SyntaxError: missing ( before formal parameters

http://jsfiddle.net/38wcndvb/

推荐答案

您的代码有几个错误:

首先,update-ui应该没有破折号.在JavaScript中,约定是使用camelCase.

First, update-ui should have no dash. In JavaScript, the convention is to use camelCase.

所以updateUi应该是:

So updateUi would be:

var updateUi = function (event) {
   event.preventdDefault();
   $("span.show_hide").toggleClass("shown hidden");
   $("table").toggleClass("wide narrow");
};

理想情况下,这将放在您的$(function () {} );声明中.

Ideally, this would go inside your $(function () {} ); declaration.

// You only need one $(function () {} );
// This is a shortcut to the document.ready event
$(function(){ 
  // updateUi will only be available inside the scope of this anonymous function
  var updateUi = function (event) {
       event.preventDefault();
       $("span.show_hide").toggleClass("shown hidden");
       $("table").toggleClass("wide narrow");
  };

  $("a[data-toggle-description-length]='toggle'").click(function(event){
    updateUi(event);
    $.get('/toggle_full_details');
  }); 

  $("a[data-toggle-description-length-refocus]='toggle'").click(function(event){
    updateUi(event);
    $("input[type='text']:first").focus();   // focus
    $.get('/toggle_full_details');
  });
});

如果需要使updateUi函数全局可用,则可以在$(function () {} );外部声明它.

If you need to make the updateUi function available globally, you can just declare it outside your $(function () {} );.

这篇关于将常见逻辑提取到JavaScript中的可重用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆